<template>
  <div class="learning-report">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="back-btn" @click="goBack">
        ← 返回
      </button>
      <h1>📊 学习报告</h1>
    </div>

    <!-- 标签页 -->
    <div class="tabs">
      <button
        :class="['tab-btn', { active: activeTab === 'dashboard' }]"
        @click="activeTab = 'dashboard'"
      >
        📈 数据仪表盘
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'analysis' }]"
        @click="activeTab = 'analysis'"
      >
        🔍 学习记录分析
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'guidance' }]"
        @click="activeTab = 'guidance'"
      >
        ✍️ 个性化指导
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'push' }]"
        @click="activeTab = 'push'"
      >
        📤 推送推荐
      </button>
    </div>

    <!-- 数据仪表盘 -->
    <div v-if="activeTab === 'dashboard'" class="tab-content">
      <div class="section-header">
        <h2>学生学习报告 - 数据仪表盘</h2>
        <select v-model="selectedClass" class="class-select">
          <option value="">全部班级</option>
          <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
            {{ classItem.name }}
          </option>
        </select>
      </div>

      <!-- 班级整体学习数据概览 -->
      <div class="dashboard-overview">
        <div class="stat-card">
          <div class="stat-icon">👥</div>
          <div class="stat-info">
            <div class="stat-value">{{ classStats.totalStudents }}</div>
            <div class="stat-label">总学生数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">📚</div>
          <div class="stat-info">
            <div class="stat-value">{{ classStats.avgProgress }}%</div>
            <div class="stat-label">平均学习进度</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">⏱️</div>
          <div class="stat-info">
            <div class="stat-value">{{ classStats.avgStudyTime }}</div>
            <div class="stat-label">平均学习时长</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">🎯</div>
          <div class="stat-info">
            <div class="stat-value">{{ classStats.completionRate }}%</div>
            <div class="stat-label">完成率</div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <div class="chart-card">
          <h3>学习进度趋势</h3>
          <div class="chart-placeholder">
            <p>📊 图表区域（待实现）</p>
          </div>
        </div>
        <div class="chart-card">
          <h3>学习时长分布</h3>
          <div class="chart-placeholder">
            <p>📊 图表区域（待实现）</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 学习记录分析 -->
    <div v-if="activeTab === 'analysis'" class="tab-content">
      <div class="section-header">
        <h2>分析学习记录</h2>
        <div class="header-actions">
          <select v-model="analysisClass" class="class-select">
            <option value="">全部班级</option>
            <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
              {{ classItem.name }}
            </option>
          </select>
          <button class="btn-primary" @click="generateAnalysis">
            🔄 生成分析报告
          </button>
        </div>
      </div>

      <div class="analysis-content">
        <div class="analysis-section">
          <h3>学习记录详情</h3>
          <div class="record-table">
            <table>
              <thead>
                <tr>
                  <th>学生姓名</th>
                  <th>学习内容</th>
                  <th>学习时长</th>
                  <th>完成度</th>
                  <th>学习时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="record in learningRecords" :key="record.id">
                  <td>{{ record.studentName }}</td>
                  <td>{{ record.content }}</td>
                  <td>{{ record.duration }}</td>
                  <td>
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: record.completion + '%' }"></div>
                      <span class="progress-text">{{ record.completion }}%</span>
                    </div>
                  </td>
                  <td>{{ record.studyTime }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="analysis-section">
          <h3>分析结果</h3>
          <div class="analysis-result">
            <p>{{ analysisResult || '点击"生成分析报告"按钮生成分析结果' }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 个性化指导 -->
    <div v-if="activeTab === 'guidance'" class="tab-content guidance-content">
      <div class="section-header">
        <h2>个性化指导面板</h2>
        <button class="btn-primary" @click="saveGuidance">
          💾 保存指导
        </button>
      </div>

      <div class="guidance-layout">
        <!-- 侧边栏：儿童列表和关键指标 -->
        <div class="sidebar">
          <h3>学生列表</h3>
          <div class="student-list">
            <div
              v-for="student in students"
              :key="student.id"
              :class="['student-item', { active: selectedStudent?.id === student.id }]"
              @click="selectStudent(student)"
            >
              <div class="student-name">{{ student.name }}</div>
              <div class="student-metrics">
                <div class="metric">
                  <span class="metric-label">进度:</span>
                  <span class="metric-value">{{ student.progress }}%</span>
                </div>
                <div class="metric">
                  <span class="metric-label">时长:</span>
                  <span class="metric-value">{{ student.studyTime }}</span>
                </div>
                <div class="metric">
                  <span class="metric-label">完成度:</span>
                  <span class="metric-value">{{ student.completion }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 主区域：富文本编辑器 -->
        <div class="main-editor">
          <div v-if="selectedStudent" class="editor-header">
            <h3>为 {{ selectedStudent.name }} 撰写指导</h3>
          </div>
          <div v-else class="editor-header">
            <h3>请从左侧选择学生</h3>
          </div>
          <div class="editor-toolbar">
            <button class="toolbar-btn" @click="insertVoice">🎤 插入语音</button>
            <button class="toolbar-btn" @click="insertLink">🔗 附加课件链接</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.bold }"
              @click="formatText('bold')"
            >B</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.italic }"
              @click="formatText('italic')"
            >I</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.underline }"
              @click="formatText('underline')"
            >U</button>
          </div>
          
          <!-- 录音对话框 -->
          <AudioRecorder 
            :show="showAudioRecorder" 
            @close="showAudioRecorder = false"
            @insert="handleInsertAudio"
          />
          
          <!-- 课件上传对话框 -->
          <CoursewareUploadDialog 
            :show="showCoursewareUpload" 
            @close="showCoursewareUpload = false"
            @insert="handleInsertCourseware"
          />
          
          <!-- 预览对话框 -->
          <div v-if="showPreviewModal" class="preview-modal-overlay" @click.self="showPreviewModal = false">
            <div class="preview-modal" @click.stop>
              <div class="preview-header">
                <h3>预览指导内容 - {{ selectedStudent?.name }}</h3>
                <button class="close-btn" @click="showPreviewModal = false">×</button>
              </div>
              <div class="preview-toolbar">
                <label class="checkbox-label">
                  <input 
                    type="checkbox" 
                    :checked="selectedPreviewItems.length === previewItems.length && previewItems.length > 0"
                    @change="toggleSelectAll"
                  />
                  全选
                </label>
                <button 
                  class="btn-danger" 
                  :disabled="selectedPreviewItems.length === 0"
                  @click="deleteSelectedItems"
                >
                  🗑️ 删除选中项 ({{ selectedPreviewItems.length }})
                </button>
              </div>
              <div class="preview-content-wrapper">
                <div class="preview-content" v-html="previewContent"></div>
              </div>
              <div class="preview-footer">
                <button class="btn-secondary" @click="showPreviewModal = false">关闭</button>
              </div>
            </div>
          </div>
          
          <div
            class="rich-editor"
            contenteditable="true"
            ref="richEditor"
            @input="updateEditorContent"
            @compositionstart="onCompositionStart"
            @compositionend="onCompositionEnd"
            @click="handleEditorClickAndCheckFormat"
            @keyup="checkFormatState"
            placeholder="在此输入指导内容..."
          ></div>
          <div class="editor-footer">
            <button class="btn-secondary" @click="previewGuidance">👁️ 预览</button>
            <button class="btn-primary" @click="sendGuidance">📤 发送指导</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 推送推荐 -->
    <div v-if="activeTab === 'push'" class="tab-content">
      <div class="section-header">
        <h2>推送推荐</h2>
        <button class="btn-secondary" @click="showBatchPanel = !showBatchPanel">
          📋 批量操作
        </button>
      </div>

      <!-- 批量操作面板 -->
      <div v-if="showBatchPanel" class="batch-panel">
        <h3>批量操作面板</h3>
        <div class="batch-controls">
          <div class="filter-group">
            <label>按班级筛选：</label>
            <select v-model="batchSelectedClass" class="class-select">
              <option value="">全部班级</option>
              <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
                {{ classItem.name }}
              </option>
            </select>
          </div>
          <div class="checkbox-group">
            <label>
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              全选推荐内容
            </label>
          </div>
          <button class="btn-primary" @click="batchPushRecommend">
            🚀 一键推送
          </button>
        </div>
      </div>

      <!-- 推荐内容列表 -->
      <div class="recommend-list">
        <div class="recommend-type-selector">
          <button
            :class="['type-btn', { active: pushType === 'courseware' }]"
            @click="pushType = 'courseware'"
          >
            📄 课件推荐
          </button>
          <button
            :class="['type-btn', { active: pushType === 'picturebook' }]"
            @click="pushType = 'picturebook'"
          >
            📚 绘本推荐
          </button>
          <button
            :class="['type-btn', { active: pushType === 'guidance' }]"
            @click="pushType = 'guidance'"
          >
            ✍️ 学习指导
          </button>
        </div>

        <div class="push-content">
          <div v-if="pushType === 'courseware'" class="content-list">
            <div class="content-card" v-for="courseware in coursewares" :key="courseware.id">
              <div class="content-header">
                <h3>{{ courseware.title }}</h3>
                <span class="content-meta">大小: {{ courseware.size }}</span>
              </div>
              <div class="content-actions">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="courseware.selected" />
                  推送
                </label>
              </div>
            </div>
          </div>

          <div v-if="pushType === 'picturebook'" class="content-list">
            <div class="content-card" v-for="book in picturebooks" :key="book.id">
              <div class="content-header">
                <h3>{{ book.title }}</h3>
                <span class="content-meta">作者: {{ book.author }}</span>
              </div>
              <div class="content-actions">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="book.selected" />
                  推送
                </label>
              </div>
            </div>
          </div>

          <div v-if="pushType === 'guidance'" class="guidance-list">
            <div class="guidance-card" v-for="guidance in guidanceList" :key="guidance.id">
              <div class="guidance-header">
                <h3>{{ guidance.studentName }} - {{ guidance.title }}</h3>
                <span class="guidance-meta">创建时间: {{ guidance.createTime }}</span>
              </div>
              <div class="guidance-preview" v-html="guidance.preview"></div>
              <div class="content-actions">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="guidance.selected" />
                  推送
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AudioRecorder from '@/components/AudioRecorder.vue';
import CoursewareUploadDialog from '@/components/CoursewareUploadDialog.vue';
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'LearningReport',
  components: {
    AudioRecorder,
    CoursewareUploadDialog
  },
  data() {
    return {
      activeTab: 'dashboard',
      selectedClass: '',
      analysisClass: '',
      showBatchPanel: false,
      batchSelectedClass: '',
      selectAll: false,
      pushType: 'courseware',
      selectedStudent: null,
      editorContent: '',
      isComposing: false, // 输入法组合状态
      analysisResult: '',
      activeFormats: {
        bold: false,
        italic: false,
        underline: false
      },
      showAudioRecorder: false,
      showCoursewareUpload: false,
      showPreviewModal: false,
      previewContent: '',
      previewItems: [], // 预览中的可删除项（音频和文件）
      selectedPreviewItems: [], // 选中的预览项
      classes: [
        { id: 1, name: '幼儿英语启蒙班' },
        { id: 2, name: '少儿英语基础班' },
        { id: 3, name: '少儿英语进阶班' }
      ],
      classStats: {
        totalStudents: 45,
        avgProgress: 68,
        avgStudyTime: '2.5小时',
        completionRate: 75
      },
      students: [
        { id: 1, name: '小明', progress: 65, studyTime: '2小时', completion: 70 },
        { id: 2, name: '小红', progress: 80, studyTime: '3小时', completion: 85 },
        { id: 3, name: '小刚', progress: 45, studyTime: '1.5小时', completion: 50 }
      ],
      learningRecords: [
        { id: 1, studentName: '小明', content: '基础单词学习', duration: '30分钟', completion: 70, studyTime: '2024-01-15 10:00' },
        { id: 2, studentName: '小红', content: '绘本阅读', duration: '45分钟', completion: 85, studyTime: '2024-01-15 14:00' },
        { id: 3, studentName: '小刚', content: '听力训练', duration: '20分钟', completion: 50, studyTime: '2024-01-15 16:00' }
      ],
      coursewares: [
        { id: 1, title: '基础单词课件', size: '15.2MB', selected: false },
        { id: 2, title: '语法练习课件', size: '22.8MB', selected: false }
      ],
      picturebooks: [
        { id: 1, title: 'The Very Hungry Caterpillar', author: 'Eric Carle', selected: false },
        { id: 2, title: 'Where the Wild Things Are', author: 'Maurice Sendak', selected: false }
      ],
      guidanceList: [
        { id: 1, studentName: '小明', title: '学习指导', createTime: '2024-01-15', preview: '小明同学在学习单词方面表现良好...', selected: false },
        { id: 2, studentName: '小红', title: '学习指导', createTime: '2024-01-16', preview: '小红同学在阅读方面进步明显...', selected: false }
      ]
    };
  },
  mounted() {
    // 确保编辑器中的删除按钮可以正常工作
    this.$nextTick(() => {
      this.setupEditorEventListeners();
      // 初始化编辑器内容
      if (this.$refs.richEditor && this.editorContent) {
        this.$refs.richEditor.innerHTML = this.editorContent;
      }
    });
  },
  watch: {
    editorContent() {
      // 当编辑器内容更新时，重新设置事件监听器
      // 注意：不要在这里更新innerHTML，避免与输入法冲突
      this.$nextTick(() => {
        this.setupEditorEventListeners();
      });
    },
    activeTab(newTab) {
      // 切换到个性化指导标签时，初始化编辑器内容
      if (newTab === 'guidance') {
        this.$nextTick(() => {
          if (this.$refs.richEditor && this.editorContent) {
            this.$refs.richEditor.innerHTML = this.editorContent;
          }
        });
      }
    }
  },
  methods: {
    setupEditorEventListeners() {
      // 为编辑器中的删除按钮设置事件监听器
      const editor = this.$refs.richEditor || document.querySelector('.rich-editor');
      if (editor) {
        // 移除旧的事件监听器（如果存在）
        const newHandler = (e) => this.handleEditorClick(e);
        editor._deleteHandler = newHandler;
        editor.addEventListener('click', newHandler);
      }
    },
    goBack() {
      this.$router.push('/');
    },
    generateAnalysis() {
      this.analysisResult = '分析报告已生成：\n1. 整体学习进度良好\n2. 部分学生需要加强听力训练\n3. 建议增加互动性学习内容';
    },
    selectStudent(student) {
      this.selectedStudent = student;
      // 保留原有的编辑器内容，或者初始化新内容
      if (!this.editorContent || this.editorContent.trim() === '' || this.editorContent.includes('撰写的学习指导...')) {
        this.editorContent = `为 ${student.name} 撰写的学习指导...`;
        // 更新编辑器显示
        this.$nextTick(() => {
          if (this.$refs.richEditor) {
            this.$refs.richEditor.innerHTML = this.editorContent;
          }
        });
      }
    },
    // 输入法开始组合
    onCompositionStart() {
      this.isComposing = true;
    },

    // 输入法结束组合
    onCompositionEnd(event) {
      this.isComposing = false;
      // 组合结束后更新内容
      this.$nextTick(() => {
        this.updateEditorContent(event);
      });
    },

    // 更新编辑器内容
    updateEditorContent(event) {
      // 如果正在输入法组合中，不更新内容（避免中间状态）
      if (this.isComposing) {
        return;
      }
      
      const element = event.target;
      if (!element) return;
      
      // 保存HTML内容用于富文本显示
      // 清理可能的输入法残留标记
      let htmlContent = element.innerHTML;
      
      // 移除输入法相关的标记（如果有）
      htmlContent = htmlContent.replace(/<mark[^>]*>.*?<\/mark>/gi, '');
      
      this.editorContent = htmlContent;
    },
    handleEditorClickAndCheckFormat(event) {
      // 处理删除按钮点击
      if (event.target.classList.contains('delete-btn')) {
        event.preventDefault();
        event.stopPropagation();
        const item = event.target.closest('.editable-item');
        if (item) {
          // 确认删除
          if (confirm('确定要删除这个' + (item.classList.contains('audio-embed') ? '语音' : '文件') + '吗？')) {
            item.remove();
            // 更新编辑器内容
            if (this.$refs.richEditor) {
              this.updateEditorContent({ target: this.$refs.richEditor });
            }
          }
        }
        return;
      }
      
      // 检查格式状态
      this.$nextTick(() => {
        this.checkFormatState();
      });
    },
    formatText(type) {
      const editor = this.$refs.richEditor || document.querySelector('.rich-editor');
      if (!editor) return;
      
      editor.focus();
      
      // 检查是否有选中的文字
      const selection = window.getSelection();
      const hasSelection = selection && selection.toString().trim().length > 0;
      
      // 如果没有选中文字，选中全部文字
      if (!hasSelection) {
        const range = document.createRange();
        range.selectNodeContents(editor);
        selection.removeAllRanges();
        selection.addRange(range);
      }
      
      // 切换格式状态
      if (type === 'bold') {
        this.activeFormats.bold = !this.activeFormats.bold;
      } else if (type === 'italic') {
        this.activeFormats.italic = !this.activeFormats.italic;
      } else if (type === 'underline') {
        this.activeFormats.underline = !this.activeFormats.underline;
      }
      
      // 执行格式化命令
      document.execCommand(type, false, null);
      
      // 如果没有选中文字，取消选中（避免全部文字被选中）
      if (!hasSelection) {
        selection.removeAllRanges();
        // 将光标移到末尾
        const range = document.createRange();
        range.collapse(false);
        selection.addRange(range);
      }
      
      // 检查当前选中文本的格式状态
      this.$nextTick(() => {
        this.checkFormatState();
      });
    },
    
    // 检查当前选中文本的格式状态
    checkFormatState() {
      const editor = this.$refs.richEditor || document.querySelector('.rich-editor');
      if (!editor) return;
      
      try {
        // 检查当前格式状态
        this.activeFormats.bold = document.queryCommandState('bold');
        this.activeFormats.italic = document.queryCommandState('italic');
        this.activeFormats.underline = document.queryCommandState('underline');
      } catch (e) {
        // 如果queryCommandState不支持，忽略错误
        console.debug('格式状态检查失败:', e);
      }
    },
    insertVoice() {
      if (!this.selectedStudent) {
        alert('请先选择学生');
        return;
      }
      this.showAudioRecorder = true;
    },
    insertLink() {
      if (!this.selectedStudent) {
        alert('请先选择学生');
        return;
      }
      this.showCoursewareUpload = true;
    },
    handleInsertAudio(audioData) {
      // 插入音频到编辑器
      const editor = document.querySelector('.rich-editor');
      if (editor) {
        // 确保URL是完整的
        let audioUrl = audioData.url;
        if (audioUrl && !audioUrl.startsWith('http')) {
          // 如果是相对路径，添加服务器地址
          const baseUrl = childEnglishApi.getCurrentServer();
          if (audioUrl.startsWith('/')) {
            audioUrl = baseUrl + audioUrl;
          } else {
            audioUrl = baseUrl + '/' + audioUrl;
          }
        }
        const audioId = 'audio_' + Date.now();
        const audioHtml = `
          <div class="audio-embed editable-item" data-audio-id="${audioId}" data-audio-url="${audioUrl}" data-audio-duration="${audioData.duration}">
            <div class="audio-content">
              <div class="audio-info">
                <audio controls src="${audioUrl}"></audio>
                <span class="audio-meta">语音指导 (时长: ${this.formatTime(audioData.duration)})</span>
              </div>
            </div>
            <button class="delete-btn" data-action="delete-audio" title="删除语音">×</button>
          </div>
        `;
        // 将音频插入到编辑器末尾（在所有附件之后）
        const range = document.createRange();
        range.selectNodeContents(editor);
        range.collapse(false); // 折叠到末尾
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('insertHTML', false, audioHtml);
        this.updateEditorContent({ target: editor });
      }
    },
    handleInsertCourseware(fileData) {
      // 插入课件链接到编辑器
      const editor = document.querySelector('.rich-editor');
      if (editor) {
        // 确保URL是完整的
        let fileUrl = fileData.url;
        if (fileUrl && !fileUrl.startsWith('http')) {
          // 如果是相对路径，添加服务器地址
          const baseUrl = childEnglishApi.getCurrentServer();
          if (fileUrl.startsWith('/')) {
            fileUrl = baseUrl + fileUrl;
          } else {
            fileUrl = baseUrl + '/' + fileUrl;
          }
        }
        const fileId = 'file_' + Date.now();
        const fileHtml = `
          <div class="courseware-link editable-item" data-file-id="${fileId}" data-file-url="${fileUrl}">
            <a href="${fileUrl}" target="_blank" class="file-content">
              <div class="file-info">
                <span class="file-name">${fileData.fileName}</span>
                <span class="file-meta">${this.formatFileSize(fileData.fileSize)}</span>
              </div>
            </a>
            <button class="delete-btn" data-action="delete-file" title="删除文件">×</button>
          </div>
        `;
        // 查找第一个音频附件的位置，将文件插入到音频之前
        // 如果没有音频，则插入到末尾
        const audioEmbeds = editor.querySelectorAll('.audio-embed');
        if (audioEmbeds.length > 0) {
          // 如果有音频，插入到第一个音频之前
          const firstAudio = audioEmbeds[0];
          const range = document.createRange();
          range.setStartBefore(firstAudio);
          range.collapse(true);
          const selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
        } else {
          // 如果没有音频，插入到末尾
          const range = document.createRange();
          range.selectNodeContents(editor);
          range.collapse(false);
          const selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
        }
        document.execCommand('insertHTML', false, fileHtml);
        this.updateEditorContent({ target: editor });
      }
    },
    getFileIcon(fileType) {
      if (!fileType) return '📄';
      if (fileType.includes('pdf')) return '📕';
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return '📊';
      if (fileType.includes('word') || fileType.includes('document')) return '📝';
      if (fileType.includes('excel') || fileType.includes('spreadsheet')) return '📈';
      if (fileType.includes('image')) return '🖼️';
      if (fileType.includes('video')) return '🎬';
      if (fileType.includes('audio')) return '🎵';
      if (fileType.includes('zip') || fileType.includes('rar')) return '📦';
      return '📄';
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    saveGuidance() {
      if (!this.selectedStudent) {
        alert('请先选择学生');
        return;
      }
      alert('指导内容已保存');
    },
    previewGuidance() {
      if (!this.selectedStudent) {
        alert('请先选择学生');
        return;
      }
      // 重置选中项
      this.selectedPreviewItems = [];
      this.previewItems = [];
      // 处理预览内容，确保音频和文件链接正确，并添加复选框
      this.previewContent = this.processPreviewContent(this.editorContent);
      // 显示预览对话框
      this.showPreviewModal = true;
      // 等待DOM更新后设置事件监听器
      this.$nextTick(() => {
        this.setupPreviewCheckboxes();
      });
    },
    processPreviewContent(content) {
      // 处理预览内容，确保所有相对URL都转换为绝对URL，并为每个可删除项添加复选框
      if (!content) return '';
      
      let processedContent = content;
      const baseUrl = childEnglishApi.getCurrentServer();
      this.previewItems = [];
      
      // 创建一个临时DOM元素来解析HTML
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = content;
      
      // 处理音频项
      const audioEmbeds = tempDiv.querySelectorAll('.audio-embed');
      audioEmbeds.forEach((audioEmbed) => {
        const audioId = audioEmbed.getAttribute('data-audio-id') || 'audio_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        let audioUrl = audioEmbed.getAttribute('data-audio-url') || '';
        const duration = audioEmbed.getAttribute('data-audio-duration') || '0';
        
        // 确保audioId存在
        if (!audioEmbed.getAttribute('data-audio-id')) {
          audioEmbed.setAttribute('data-audio-id', audioId);
        }
        
        // 转换URL为绝对URL
        if (audioUrl && !audioUrl.startsWith('http')) {
          if (audioUrl.startsWith('/')) {
            audioUrl = baseUrl + audioUrl;
          } else {
            audioUrl = baseUrl + '/' + audioUrl;
          }
          audioEmbed.setAttribute('data-audio-url', audioUrl);
        }
        
        // 更新audio标签的src
        const audioTag = audioEmbed.querySelector('audio');
        if (audioTag && audioUrl) {
          audioTag.src = audioUrl;
        }
        
        // 添加到预览项列表
        this.previewItems.push({
          id: audioId,
          type: 'audio',
          url: audioUrl,
          originalUrl: audioEmbed.getAttribute('data-audio-url'),
          duration: duration
        });
        
        // 包装音频项，添加复选框（复选框在右边）
        // 检查是否已经被包装
        if (audioEmbed.parentNode && audioEmbed.parentNode.classList.contains('preview-item-wrapper')) {
          // 已经包装过了，只更新复选框
          const existingWrapper = audioEmbed.parentNode;
          const existingCheckbox = existingWrapper.querySelector('.preview-item-checkbox');
          if (existingCheckbox) {
            existingCheckbox.setAttribute('data-item-id', audioId);
          }
        } else {
          // 创建新的包装器
          const wrapper = document.createElement('div');
          wrapper.className = 'preview-item-wrapper';
          // 先将音频项添加到包装器
          if (audioEmbed.parentNode) {
            audioEmbed.parentNode.insertBefore(wrapper, audioEmbed);
          }
          wrapper.appendChild(audioEmbed);
          // 然后在右边添加复选框
          const checkboxLabel = document.createElement('label');
          checkboxLabel.className = 'preview-checkbox-label';
          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.className = 'preview-item-checkbox';
          checkbox.setAttribute('data-item-id', audioId);
          checkboxLabel.appendChild(checkbox);
          wrapper.appendChild(checkboxLabel);
        }
      });
      
      // 处理文件项
      const coursewareLinks = tempDiv.querySelectorAll('.courseware-link');
      coursewareLinks.forEach((coursewareLink) => {
        const fileId = coursewareLink.getAttribute('data-file-id') || 'file_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        let fileUrl = coursewareLink.getAttribute('data-file-url') || '';
        
        // 确保fileId存在
        if (!coursewareLink.getAttribute('data-file-id')) {
          coursewareLink.setAttribute('data-file-id', fileId);
        }
        
        // 转换URL为绝对URL
        if (fileUrl && !fileUrl.startsWith('http') && !fileUrl.startsWith('#')) {
          if (fileUrl.startsWith('/')) {
            fileUrl = baseUrl + fileUrl;
          } else {
            fileUrl = baseUrl + '/' + fileUrl;
          }
          coursewareLink.setAttribute('data-file-url', fileUrl);
        }
        
        // 更新链接的href
        const linkTag = coursewareLink.querySelector('a.file-content');
        if (linkTag && fileUrl) {
          linkTag.href = fileUrl;
        }
        
        // 提取文件名
        const fileNameEl = coursewareLink.querySelector('.file-name');
        const fileName = fileNameEl ? fileNameEl.textContent : '未知文件';
        
        // 添加到预览项列表
        this.previewItems.push({
          id: fileId,
          type: 'file',
          url: fileUrl,
          originalUrl: coursewareLink.getAttribute('data-file-url'),
          fileName: fileName
        });
        
        // 包装文件项，添加复选框（复选框在右边）
        // 检查是否已经被包装
        if (coursewareLink.parentNode && coursewareLink.parentNode.classList.contains('preview-item-wrapper')) {
          // 已经包装过了，只更新复选框
          const existingWrapper = coursewareLink.parentNode;
          const existingCheckbox = existingWrapper.querySelector('.preview-item-checkbox');
          if (existingCheckbox) {
            existingCheckbox.setAttribute('data-item-id', fileId);
          }
        } else {
          // 创建新的包装器
          const wrapper = document.createElement('div');
          wrapper.className = 'preview-item-wrapper';
          // 先将文件项添加到包装器
          if (coursewareLink.parentNode) {
            coursewareLink.parentNode.insertBefore(wrapper, coursewareLink);
          }
          wrapper.appendChild(coursewareLink);
          // 然后在右边添加复选框
          const checkboxLabel = document.createElement('label');
          checkboxLabel.className = 'preview-checkbox-label';
          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.className = 'preview-item-checkbox';
          checkbox.setAttribute('data-item-id', fileId);
          checkboxLabel.appendChild(checkbox);
          wrapper.appendChild(checkboxLabel);
        }
      });
      
      return tempDiv.innerHTML;
    },
    setupPreviewCheckboxes() {
      // 为预览对话框中的复选框设置事件监听器
      const checkboxes = document.querySelectorAll('.preview-item-checkbox');
      checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', (e) => {
          const itemId = e.target.getAttribute('data-item-id');
          if (e.target.checked) {
            if (!this.selectedPreviewItems.includes(itemId)) {
              this.selectedPreviewItems.push(itemId);
            }
          } else {
            const index = this.selectedPreviewItems.indexOf(itemId);
            if (index > -1) {
              this.selectedPreviewItems.splice(index, 1);
            }
          }
        });
      });
    },
    toggleSelectAll(event) {
      if (event.target.checked) {
        // 全选
        this.selectedPreviewItems = this.previewItems.map(item => item.id);
        const checkboxes = document.querySelectorAll('.preview-item-checkbox');
        checkboxes.forEach(checkbox => {
          checkbox.checked = true;
        });
      } else {
        // 取消全选
        this.selectedPreviewItems = [];
        const checkboxes = document.querySelectorAll('.preview-item-checkbox');
        checkboxes.forEach(checkbox => {
          checkbox.checked = false;
        });
      }
    },
    deleteSelectedItems() {
      if (this.selectedPreviewItems.length === 0) {
        alert('请先选择要删除的项');
        return;
      }
      
      if (!confirm(`确定要删除选中的 ${this.selectedPreviewItems.length} 项吗？`)) {
        return;
      }
      
      // 从编辑器中删除选中的项
      const editor = this.$refs.richEditor || document.querySelector('.rich-editor');
      if (editor) {
        this.selectedPreviewItems.forEach(itemId => {
          // 在编辑器中查找对应的项并删除
          const item = editor.querySelector(`[data-audio-id="${itemId}"], [data-file-id="${itemId}"]`);
          if (item) {
            item.remove();
          }
        });
        
        // 更新编辑器内容
        this.updateEditorContent({ target: editor });
      }
      
      // 从预览项列表中移除
      this.previewItems = this.previewItems.filter(item => !this.selectedPreviewItems.includes(item.id));
      this.selectedPreviewItems = [];
      
      // 重新处理预览内容
      this.previewContent = this.processPreviewContent(this.editorContent);
      
      // 重新设置复选框事件监听器
      this.$nextTick(() => {
        this.setupPreviewCheckboxes();
      });
      
      alert('删除成功');
    },
    sendGuidance() {
      if (!this.selectedStudent) {
        alert('请先选择学生');
        return;
      }
      alert('指导已发送');
    },
    toggleSelectAll() {
      const items = this.pushType === 'courseware' ? this.coursewares :
                   this.pushType === 'picturebook' ? this.picturebooks :
                   this.guidanceList;
      items.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    batchPushRecommend() {
      const items = this.pushType === 'courseware' ? this.coursewares :
                   this.pushType === 'picturebook' ? this.picturebooks :
                   this.guidanceList;
      const selected = items.filter(item => item.selected);
      const className = this.batchSelectedClass ?
        this.classes.find(c => c.id === this.batchSelectedClass)?.name : '全部班级';
      alert(`将向${className}推送${selected.length}个${this.pushType === 'courseware' ? '课件' : this.pushType === 'picturebook' ? '绘本' : '学习指导'}`);
    }
  }
};
</script>

<style scoped>
.learning-report {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.back-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #2980b9;
  transform: translateX(-3px);
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2em;
}

.tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  background: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
}

.tab-btn {
  flex: 1;
  min-width: 120px;
  padding: 15px 20px;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.tab-btn:hover {
  background: #e9ecef;
}

.tab-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.tab-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  flex-wrap: wrap;
  gap: 15px;
}

.section-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.class-select {
  padding: 10px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
}

.btn-primary {
  padding: 12px 24px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}

.btn-secondary {
  padding: 12px 24px;
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #7f8c8d;
}

/* 数据仪表盘样式 */
.dashboard-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 3em;
}

.stat-value {
  font-size: 2em;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9em;
  opacity: 0.9;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 12px;
  border: 2px solid #e0e0e0;
}

.chart-card h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  color: #7f8c8d;
}

/* 分析页面样式 */
.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.analysis-section h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.record-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: #f8f9fa;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

th {
  font-weight: bold;
  color: #2c3e50;
}

.progress-bar {
  position: relative;
  width: 100px;
  height: 20px;
  background: #ecf0f1;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: bold;
  color: #2c3e50;
  z-index: 1;
}

.analysis-result {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #3498db;
  white-space: pre-line;
  color: #2c3e50;
}

/* 个性化指导页面样式 */
.guidance-content {
  padding: 0;
}

.guidance-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 300px);
  min-height: 600px;
}

.sidebar {
  width: 300px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  overflow-y: auto;
}

.sidebar h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.student-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.student-item {
  background: white;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.student-item:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.student-item.active {
  border-color: #667eea;
  background: #e8f0fe;
}

.student-name {
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 10px;
}

.student-metrics {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.metric {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.metric-label {
  color: #7f8c8d;
}

.metric-value {
  color: #2c3e50;
  font-weight: bold;
}

.main-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.editor-header h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.editor-toolbar {
  display: flex;
  gap: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.toolbar-btn {
  padding: 8px 16px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  color: #2c3e50;
}

.toolbar-btn:hover {
  background: #e9ecef;
}

.toolbar-btn.active {
  background: #95a5a6;
  color: white;
  border-color: #95a5a6;
}

.toolbar-btn.active:hover {
  background: #7f8c8d;
  border-color: #7f8c8d;
}

.rich-editor {
  flex: 1;
  min-height: 400px;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow-y: auto;
  outline: none;
  line-height: 1.6;
}

/* 确保编辑器中的内容整齐排列 */
.rich-editor > * {
  margin: 12px 0;
}

.rich-editor > *:first-child {
  margin-top: 0;
}

.rich-editor > *:last-child {
  margin-bottom: 0;
}

/* 编辑器中的文本段落样式 */
.rich-editor p {
  margin: 8px 0;
  line-height: 1.8;
}

.rich-editor p:first-child {
  margin-top: 0;
}

.rich-editor p:last-child {
  margin-bottom: 0;
}

/* 确保音频和文件项目之间有清晰的间距 */
.rich-editor .audio-embed + .audio-embed,
.rich-editor .courseware-link + .courseware-link,
.rich-editor .audio-embed + .courseware-link,
.rich-editor .courseware-link + .audio-embed {
  margin-top: 16px;
}

/* 指导意见和附件之间的间距 */
.rich-editor p + .audio-embed,
.rich-editor p + .courseware-link,
.rich-editor br + .audio-embed,
.rich-editor br + .courseware-link {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

/* 确保第一个附件前有分隔线（如果有文本内容） */
.rich-editor:not(:empty) > .audio-embed:first-of-type,
.rich-editor:not(:empty) > .courseware-link:first-of-type {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.rich-editor:empty:before {
  content: attr(placeholder);
  color: #7f8c8d;
}

.editor-footer {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

/* 推送推荐页面样式 */
.batch-panel {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 25px;
  border: 2px solid #e0e0e0;
}

.batch-panel h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.batch-controls {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: bold;
  color: #2c3e50;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: bold;
  color: #2c3e50;
}

.recommend-type-selector {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
}

.type-btn {
  padding: 12px 24px;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.type-btn:hover {
  background: #e9ecef;
}

.type-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.content-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.content-card {
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s;
}

.content-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.content-header {
  margin-bottom: 15px;
}

.content-header h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.content-meta {
  color: #7f8c8d;
  font-size: 14px;
}

.content-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  font-size: 14px;
  color: #2c3e50;
}

.guidance-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.guidance-card {
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s;
}

.guidance-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.guidance-header {
  margin-bottom: 15px;
}

.guidance-header h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.guidance-meta {
  color: #7f8c8d;
  font-size: 14px;
}

.guidance-preview {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  color: #2c3e50;
}

/* 预览对话框样式 */
.preview-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.preview-modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.preview-header h3 {
  margin: 0;
  color: #2c3e50;
}

.preview-header .close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #7f8c8d;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  transition: color 0.3s;
}

.preview-header .close-btn:hover {
  color: #e74c3c;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  background: #f8f9fa;
}

.preview-toolbar .checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.preview-toolbar .checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.preview-toolbar .btn-danger {
  padding: 8px 16px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.preview-toolbar .btn-danger:hover:not(:disabled) {
  background: #c0392b;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(231, 76, 60, 0.3);
}

.preview-toolbar .btn-danger:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  opacity: 0.6;
}

.preview-content-wrapper {
  flex: 1;
  overflow-y: auto;
}

.preview-content {
  padding: 20px;
  color: #2c3e50;
  line-height: 1.6;
}

.preview-item-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 15px 0;
  width: 100%;
}

.preview-checkbox-label {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin: 0;
  padding: 0;
}

.preview-checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  margin: 0;
  padding: 0;
  flex-shrink: 0;
}

.preview-content .audio-embed,
.preview-content .courseware-link {
  flex: 1;
  margin: 0;
  min-width: 0;
}

.preview-content .audio-embed {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #3498db;
  gap: 15px;
  min-height: 80px;
}

.preview-content .audio-embed .audio-content {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.preview-content .audio-embed .audio-icon {
  font-size: 28px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e8f4fe;
  border-radius: 8px;
}

.preview-content .audio-embed audio {
  width: 100%;
  max-width: 500px;
  height: 40px;
}

.preview-content .audio-embed .audio-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #7f8c8d;
}

.preview-content .courseware-link {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #2ecc71;
  gap: 15px;
  min-height: 70px;
}

.preview-content .courseware-link .file-content {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
  text-decoration: none;
  color: #2c3e50;
}

.preview-content .courseware-link .file-icon {
  font-size: 32px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e8f8f0;
  border-radius: 8px;
}

.preview-content .courseware-link .file-name {
  font-weight: bold;
  font-size: 14px;
  color: #2c3e50;
  word-break: break-all;
  margin-bottom: 4px;
}

.preview-content .courseware-link .file-meta {
  font-size: 12px;
  color: #7f8c8d;
}

.preview-content .delete-btn {
  display: flex !important; /* 预览模式下显示删除按钮 */
  visibility: visible !important;
}

.preview-footer {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}

/* 音频嵌入样式 */
.rich-editor .audio-embed {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  margin: 12px 0 !important;
  padding: 12px 15px !important;
  background: #ffffff !important;
  border-radius: 8px !important;
  border: 2px solid #e0e0e0 !important;
  border-left: 4px solid #3498db !important;
  gap: 10px !important;
  min-height: 50px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
  transition: all 0.3s !important;
  position: relative !important;
  flex-wrap: nowrap !important;
  width: 100% !important;
  box-sizing: border-box !important;
}

.rich-editor .audio-embed:hover {
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2) !important;
  border-color: #3498db !important;
  background: #f8fbff !important;
}

.rich-editor .audio-embed .audio-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
  pointer-events: none;
}

.rich-editor .audio-embed .audio-content * {
  pointer-events: auto;
}

.rich-editor .audio-embed .audio-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
}

.rich-editor .audio-embed audio {
  width: auto;
  min-width: 120px;
  max-width: 250px;
  height: 32px;
  flex-shrink: 1;
}

.rich-editor .audio-embed .audio-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

/* 课件链接样式 */
.rich-editor .courseware-link {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  margin: 12px 0 !important;
  padding: 12px 15px !important;
  background: #ffffff !important;
  border-radius: 8px !important;
  border: 2px solid #e0e0e0 !important;
  border-left: 4px solid #2ecc71 !important;
  gap: 10px !important;
  min-height: 50px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
  transition: all 0.3s !important;
  position: relative !important;
  flex-wrap: nowrap !important;
  width: 100% !important;
  box-sizing: border-box !important;
}

.rich-editor .courseware-link:hover {
  box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2) !important;
  border-color: #2ecc71 !important;
  background: #f8fff9 !important;
}

.rich-editor .courseware-link .file-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  text-decoration: none;
  color: #2c3e50;
  flex-wrap: nowrap;
  overflow: visible;
  pointer-events: auto;
}

.rich-editor .courseware-link .file-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
}

.rich-editor .courseware-link .file-name {
  font-weight: bold;
  font-size: 14px;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
  flex-shrink: 1;
}

.rich-editor .courseware-link .file-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

/* 删除按钮样式 */
.rich-editor .delete-btn {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%) !important;
  color: white !important;
  border: none !important;
  border-radius: 8px !important;
  width: 32px !important;
  height: 32px !important;
  min-width: 32px !important;
  min-height: 32px !important;
  cursor: pointer !important;
  font-size: 18px !important;
  line-height: 1 !important;
  flex-shrink: 0 !important;
  transition: all 0.3s ease !important;
  opacity: 1 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  font-weight: bold !important;
  padding: 0 !important;
  margin-left: auto !important;
  position: relative !important;
  z-index: 1000 !important;
  box-shadow: 0 2px 6px rgba(231, 76, 60, 0.3) !important;
  pointer-events: auto !important;
  user-select: none !important;
}

.rich-editor .delete-btn:hover {
  background: linear-gradient(135deg, #c0392b 0%, #a93226 100%) !important;
  transform: scale(1.1) translateY(-1px) !important;
  opacity: 1 !important;
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.5) !important;
}

.rich-editor .delete-btn:active {
  transform: scale(1.05) translateY(0) !important;
  box-shadow: 0 2px 6px rgba(231, 76, 60, 0.4) !important;
}

.rich-editor .editable-item:hover .delete-btn {
  opacity: 1 !important;
}

/* 确保删除按钮始终可见 */
.rich-editor .audio-embed .delete-btn,
.rich-editor .courseware-link .delete-btn {
  visibility: visible !important;
  display: flex !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 100 !important;
}
</style>

